//
//  UIViewController+HttpRequest.m
//  CarJX
//
//  Created by King-ChenXu on 14-9-7.
//  Copyright (c) 2014年 KK. All rights reserved.
//

#import "UIViewController+HttpRequest.h"
#import <JSONKit/JSONKit.h>

#define HOSTURL @"http://api.clejw.com/shopi/mobile/interface.do"

NSString * const CarJXNetworkingErrorDomain = @"com.wx.error.domain";


@implementation ResultMy

+(BOOL)propertyIsOptional:(NSString *)propertyName
{
    return [@[@"error"] containsObject:propertyName];
}

-(NSDictionary *)dictionaryInfo
{
     
    return self.info;
}


@end

@implementation AFJSONResponseSerializer (Custom)

static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
    if ([error.domain isEqualToString:domain] && error.code == code) {
        return YES;
    } else if (error.userInfo[NSUnderlyingErrorKey]) {
        return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
    }
    
    return NO;
}


- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/octet-stream",@"text/plain", nil];
    
    return self;
}


-(id)responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing *)error
{
    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
            return nil;
        }
    }
    
    NSError *jsonModelError ;
    
    ResultMy
    *result = [[ResultMy alloc] initWithData:data error:&jsonModelError];
    
    
    result.info = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:NULL];
   
    
    if (jsonModelError) {
        *error = [NSError errorWithDomain:CarJXNetworkingErrorDomain code:CarJXUnkownDataErrorCode userInfo:@{@"data":data}];
        return nil;
    }
    
    if (![result.flag isEqualToString:@"success"]) {
        *error = [NSError errorWithDomain:CarJXNetworkingErrorDomain code:result.error userInfo:@{@"result":result}];
        return nil;
    }
    
    return result;
}


@end


@implementation UIViewController (HttpRequest)

-(void)GET:(NSString *)urlStr params:(NSDictionary *)params success:(void (^)(ResultMy *))success failure:(void (^)(NSError *))failure
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager GET:urlStr parameters:params success:^(AFHTTPRequestOperation *operation, ResultMy
                                                    *responseObject) {
        
        NSLog(@"succuse:%@",operation.response.URL);
        
        success(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            
            NSLog(@"failuer: %@",operation.response.URL);
            
            failure(error);
        }
    }];
}

-(void)GET:(NSString *)urlStr params:(NSDictionary *)params success:(void (^)(ResultMy *))success
{
    [self GET:urlStr params:params success:success failure:nil];
}

-(void)GETWithContentType:(NSString *)type params:(NSDictionary *)params success:(void (^)(ResultMy *))success failure:(void (^)(NSError *))failure
{
    NSMutableDictionary *content = [NSMutableDictionary new];
    [content setObject:type forKey:@"type"];
    [content setObject:@"ios" forKey:@"apptype"];
//    [content setObject:@"" forKey:@"token"];
    [content addEntriesFromDictionary:params];

    NSString *urlStr = [NSString stringWithFormat:HOSTURL];
//    NSString *urlStr = [NSString stringWithFormat:@"http://tapi.clejw.com/shopi/mobile/interface.do"];
    [self GET:urlStr params:@{@"content":[content JSONString]} success:success failure:failure];
}


-(void)GETWithGasonContentType:(NSString *)type params:(NSDictionary *)params success:(void (^)(ResultMy *))success failure:(void (^)(NSError *))failure
{
    NSMutableDictionary *content = [NSMutableDictionary new];
    [content setObject:type forKey:@"type"];
    //[content setObject:@"ios" forKey:@"apptype"];
    //    [content setObject:@"" forKey:@"token"];
    [content addEntriesFromDictionary:params];
    
    NSString *urlStr = [NSString stringWithFormat:HOSTURL];
//        NSString *urlStr = [NSString stringWithFormat:@"http://tapi.clejw.com/shopi/mobile/interface.do"];
    [self GET:urlStr params:@{@"content":[content JSONString]} success:success failure:failure];
}



-(void)GETWithContentHelpType:(NSString *)type params:(NSDictionary *)params success:(void (^)(ResultMy *))success failure:(void (^)(NSError *))failure
{
    NSMutableDictionary *content = [NSMutableDictionary new];
    NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];

    [content setObject:type forKey:@"type"];
    [content setObject:@"ios" forKey:@"apptype"];
    if (deviceToken) {
        [content setObject:deviceToken forKey:@"token"];
    }else{
        [content setObject:@"" forKey:@"token"];
    }
    [content addEntriesFromDictionary:params];
    NSString *urlStr = [NSString stringWithFormat:HOSTURL];
//    NSString *urlStr = [NSString stringWithFormat:@"http://tapi.clejw.com/shopi/mobile/interface.do"];
    [self GET:urlStr params:@{@"content":[content JSONString]} success:success failure:failure];
}

-(void)GETWithContentType:(NSString *)type params:(NSDictionary *)params success:(void (^)(ResultMy *))success
{
    [self GETWithContentType:type params:params success:success failure:nil];
}

@end
